using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace TubeTest
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Matrix worldMatrix;
        Matrix cameraMatrix;
        Matrix projectionMatrix;
        float angleX = 0f;
        float angleY = 0f;

        BasicEffect cubeEffect;
        TubeObject tubeOut = new TubeObject();
        TubeObject tubeInside = new TubeObject();

        Vector3 translation = Vector3.Zero;

        RasterizerState rasterizerState = new RasterizerState() { CullMode = CullMode.None, FillMode = FillMode.WireFrame };

        public void initializeWorld()
        {
            cameraMatrix = Matrix.CreateLookAt(
                new Vector3(0, 30, 20), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                800.0f / 480.0f, 1.0f, 500.0f);
            float tilt = MathHelper.ToRadians(22.5f);
            worldMatrix = Matrix.CreateRotationX(tilt) * Matrix.CreateRotationY(tilt);

            cubeEffect = new BasicEffect(GraphicsDevice);
            cubeEffect.World = worldMatrix;
            cubeEffect.View = cameraMatrix;
            cubeEffect.Projection = projectionMatrix;
            cubeEffect.TextureEnabled = true;
            cubeEffect.LightingEnabled = true;

            cubeEffect.FogEnabled = true;
            cubeEffect.FogStart = 10.0f;
            cubeEffect.FogEnd = 150.0f;
            cubeEffect.FogColor = new Vector3(0.0f, 0.0f, 0.0f);
            
            //cubeEffect.AmbientLightColor = new Vector3(0.1f, 0.1f, 0.1f);
            cubeEffect.AmbientLightColor = new Vector3(0.5f, 0.5f, 0.5f);
            cubeEffect.PreferPerPixelLighting = true;
            cubeEffect.SpecularPower = 1.0f;
            cubeEffect.SpecularColor = new Vector3(0.0f, 0.0f, 0.0f);

            cubeEffect.DirectionalLight0.Enabled = true;
            cubeEffect.DirectionalLight0.DiffuseColor = new Vector3(0.7f, 0.7f, 0.7f);
            cubeEffect.DirectionalLight0.Direction = Vector3.Right;
            cubeEffect.DirectionalLight0.SpecularColor = Vector3.One;

            cubeEffect.DirectionalLight1.Enabled = true;
            cubeEffect.DirectionalLight1.DiffuseColor = new Vector3(1.0f, 0.7f, 0.7f);
            cubeEffect.DirectionalLight1.Direction = Vector3.Up;
            cubeEffect.DirectionalLight1.SpecularColor = Vector3.One;
            

            for (float i = -40; i <= 40; i += 0.4f)
            {
                tubeOut.addNode(i * 5.0f, (float)Math.Sin(i * 0.5f) * 20.0f, (float)Math.Cos(i * 0.32f) * 25.0f);
                tubeOut.last().radius = 5.0f + (float)Math.Sin(i * 0.4f) * 0.5f;
                tubeInside.addNode(i * 5.0f, (float)Math.Sin(i * 0.5f) * 20.0f, (float)Math.Cos(i * 0.32f) * 25.0f);
                tubeInside.last().radius = tubeOut.last().radius * 0.98f;
            }

            //tubeOut.subdivide(1);
            //tubeOut.subdivide(1);
            //tubeOut.subdivide(1);
            //tubeOut.subdivide(1);
            tubeOut.randomizeAll(0.1f);
            //tubeInside.subdivide(1);
            //tubeInside.subdivide(1);
            //tubeInside.subdivide(1);
            //tubeInside.subdivide(1);

            //tubeOut.setRadiusToAll(2.0f);
            tubeOut.recalculateGeometry(true);

            //tubeInside.setRadiusToAll(1.9f);
            tubeInside.copyDisplacements(tubeOut);
            tubeInside.recalculateGeometry(false);
        }

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();
            initializeWorld();
            Window.Title = "The Budak Project";
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            tubeOut.shapeTexture = Content.Load<Texture2D>("3408");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            if(Keyboard.GetState().IsKeyDown(Keys.Right))
                angleY -= 0.5f;

            if (Keyboard.GetState().IsKeyDown(Keys.Left))
                angleY += 0.5f;

            if (Keyboard.GetState().IsKeyDown(Keys.Down))
                angleX -= 0.5f;

            if (Keyboard.GetState().IsKeyDown(Keys.Up))
                angleX += 0.5f;

            if (Keyboard.GetState().IsKeyDown(Keys.W)) translation.Y -= 0.5f;
            if (Keyboard.GetState().IsKeyDown(Keys.S)) translation.Y += 0.5f;
            if (Keyboard.GetState().IsKeyDown(Keys.A)) translation.X += 0.5f;
            if (Keyboard.GetState().IsKeyDown(Keys.D)) translation.X -= 0.5f;
            if (Keyboard.GetState().IsKeyDown(Keys.Q)) translation.Z -= 0.5f;
            if (Keyboard.GetState().IsKeyDown(Keys.E)) translation.Z += 0.5f;

            angleX += 0.1f;
            angleY += 0.5f;

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);

            worldMatrix = Matrix.CreateRotationY(MathHelper.ToRadians(angleY)) *
                Matrix.CreateRotationX(MathHelper.ToRadians(angleX)) * Matrix.CreateTranslation(translation);
                //Matrix.CreateRotationX(MathHelper.ToRadians((float)Math.Sin(angleX) * 30.0f - 20.0f));
            cubeEffect.World = worldMatrix;

            //GraphicsDevice.RasterizerState = rasterizerState; 

            foreach (EffectPass pass in cubeEffect.CurrentTechnique.Passes)
            {
                pass.Apply();
                cubeEffect.Texture = tubeOut.shapeTexture;

                //tubeInside.RenderShape(GraphicsDevice);
                tubeOut.RenderShape(GraphicsDevice);
            }


            base.Draw(gameTime);
        }
    }
}
